// ============ AI工具调度系统 - 内置聊天工具 ============

import type { ToolDefinition } from '../types';
import { chat } from '../../../tauriApi';

/**
 * 内置 chat.complete 工具（调用 Tauri 后端）
 */
export const BUILTIN_CHAT_COMPLETE: ToolDefinition = {
  id: 'chat.complete',
  name: 'Chat Completion',
  description: 'Complete a chat conversation using the configured AI model',
  parameters: {
    type: 'object',
    required: ['messages'],
    properties: {
      messages: {
        type: 'array',
        items: {
          type: 'object',
          required: ['role', 'content'],
          properties: {
            role: { type: 'string', enum: ['user', 'assistant', 'system', 'tool'] },
            content: { type: 'string' },
            // 为第二轮对话允许工具相关字段（可选）
            name: { type: 'string' },
            tool_call_id: { type: 'string' },
            tool_calls: {
              type: 'array',
              items: {
                type: 'object',
                required: ['id', 'type', 'function'],
                properties: {
                  id: { type: 'string' },
                  type: { type: 'string', const: 'function' },
                  function: {
                    type: 'object',
                    required: ['name', 'arguments'],
                    properties: {
                      name: { type: 'string' },
                      arguments: { type: 'string' }
                    }
                  }
                }
              }
            }
          }
        }
      },
      modelKey: { type: 'string' },
      temperature: { type: 'number', minimum: 0, maximum: 2 },
      maxTokens: { type: 'integer', minimum: 1 },
      // OpenAI-style tools definition: [{ type: 'function', function: { name, description?, parameters? } }]
      tools: {
        type: 'array',
        items: {
          type: 'object',
          properties: {
            type: { type: 'string', const: 'function' },
            function: {
              type: 'object',
              required: ['name'],
              properties: {
                name: { type: 'string' },
                description: { type: 'string' },
                parameters: { type: ['object', 'null'] }
              }
            }
          },
          required: ['type', 'function']
        }
      },
      // tool_choice: 'auto' | 'none' | { type: 'function', function: { name } }
      toolChoice: {
        anyOf: [
          { type: 'string', enum: ['auto', 'none'] },
          {
            type: 'object',
            properties: {
              type: { type: 'string', const: 'function' },
              function: {
                type: 'object',
                required: ['name'],
                properties: { name: { type: 'string' } }
              }
            },
            required: ['type', 'function']
          }
        ]
      }
    }
  },
  metadata: {
    timeout: 60000, // 60秒超时（AI 调用可能较慢）
    category: 'ai',
    tags: ['chat', 'completion', 'ai']
  },
  handler: async (params, context) => {
    const { messages, modelKey = '', temperature, maxTokens, tools, toolChoice } = params;

    const request = {
      key: modelKey,
      messages,
      ...(temperature !== undefined && { temperature }),
      ...(maxTokens !== undefined && { max_tokens: maxTokens }),
      ...(tools !== undefined && { tools }),
      ...(toolChoice !== undefined && { tool_choice: toolChoice })
    };

    // 如果提供了 signal，则与实际调用竞争，尽快在前端对取消/超时做出响应
    const chatPromise = chat(request);

    if (context?.signal) {
      const abortPromise = new Promise<never>((_, reject) => {
        const s = context.signal!;
        if ((s as any).aborted) {
          reject((s as any).reason ?? new DOMException('Aborted', 'AbortError'));
          return;
        }
        const onAbort = () => {
          reject((s as any).reason ?? new DOMException('Aborted', 'AbortError'));
        };
        s.addEventListener('abort', onAbort, { once: true });
      });
      try {
        const res = await Promise.race([chatPromise, abortPromise]);
        return {
          content: (res as any).content,
          raw: (res as any).raw
        };
      } catch (error: any) {
        // 将取消/超时向上传递，让上层统一处理
        if (error?.name === 'AbortError' || /aborted|abort|TimeoutError/i.test(String(error?.message || error))) {
          throw error;
        }
        // 其他错误标准化
        throw new Error(`Chat completion failed: ${error?.message || String(error)}`);
      }
    }

    // 无 signal 的情况退化为直接调用
    try {
      const response = await chatPromise;
      return {
        content: response.content,
        raw: response.raw
      };
    } catch (error: any) {
      throw new Error(`Chat completion failed: ${error.message || error}`);
    }
  }
};